// scripts/deploy-s3.js
const fs = require('fs');
const path = require('path');
const AWS = require('aws-sdk');
const mime = require('mime-types');

// 读取命令行参数
const env = process.argv[2]; // staging/test/prod
if (!env) {
  console.error('❌ 请在命令中指定环境参数，如：node scripts/deploy-s3.js staging');
  process.exit(1);
}

// 环境配置映射
const configMap = {
  dev: {
    bucketName: 'community-webpage-dev',
  },
  staging: {
    bucketName: 'community-webpage-staging',
  },
  test: {
    bucketName: 'community-webpage-test',
  },
  prod: {
    bucketName: 'community-webpage-prod',
  },
};

// 检查环境是否有效
if (!configMap[env]) {
  console.error(`❌ 无效的环境参数：${env}，必须是 dev / staging / test / prod`);
  process.exit(1);
}

const { bucketName } = configMap[env];

// AWS S3 配置
const s3 = new AWS.S3({
  region: 'us-east-1',
  accessKeyId: 'AKIAQPDNRSTX74HPOY7K',
  secretAccessKey: '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',
});

const buildDir = path.resolve('./dist');

console.log(`🚀 开始部署到环境：${env}`);
console.log(`📦 目标 Bucket：${bucketName}`);
console.log('------------------------------------');

// 递归上传目录
function uploadDir(dir, bucketPath = '') {
  const files = fs.readdirSync(dir);
  files.forEach((file) => {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      uploadDir(fullPath, `${bucketPath}${file}/`);
    } else {
      const fileContent = fs.readFileSync(fullPath);
      const contentType = mime.lookup(fullPath) || 'application/octet-stream';
      const params = {
        Bucket: bucketName + '/online',
        Key: `${bucketPath}${file}`,
        Body: fileContent,
        ContentType: contentType,
      };
      s3.upload(params, (err, data) => {
        if (err) {
          console.error(`❌ 上传失败: ${file}`, err.message);
        } else {
          console.log(`✅ 已上传: ${data.Key}`);
        }
      });
    }
  });

  console.log('✅ 部署脚本执行完毕');
}

// 执行上传
uploadDir(buildDir);
